package com.blueocean_health.care.management.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.domain.base.SysResult;
import com.blueocean_health.care.management.domain.vo.ModuleVo;
import com.blueocean_health.care.management.em.ProjectTypeEnum;
import com.blueocean_health.care.management.mapper.ModuleMapper;
import com.blueocean_health.care.management.mapper.PowerMapper;
import com.blueocean_health.care.management.mapper.RoleMapper;
import com.blueocean_health.care.management.service.PowerService;

/**
 * 权限清单Service
 * 
 * @author huyanqiu
 * @date 2018年3月29日 上午10:33:34
 * @version 版本号：1.0
 */
@Service
public class PowerServiceImpl implements PowerService {

	@Autowired
	private PowerMapper powerMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private ModuleMapper moduleMapper;

	private Logger logger = LoggerFactory.getLogger(PowerServiceImpl.class);

	/**
	 * 获得对应组织的权限清单
	 * 
	 * @param orgId
	 *            组织id
	 * @param type
	 *            1.泰心端权限 2. 项目端权限
	 */
	@Override
	public SysResult list(String orgId, int type) {
		List<ModuleVo> powerList = new ArrayList<>();
		if (type == 1) {
			// 获取组织对应的可用模块
			String modules = moduleMapper.findByTeamId(orgId);
			Map<String, String> paramsMap = new HashMap<>();
			paramsMap.put("orgId", orgId);
			paramsMap.put("modules", modules);
			powerList = powerMapper.findPowerByOrgIdAndModules(paramsMap);
		} else if (type == 2) {
			// 获取运营端所有权限清单
			powerList = powerMapper.findAllProjectPower();
			powerList = getNewPowerList(powerList);
		}
		return SysResult.ok(powerList);
	}

	private List<ModuleVo> getNewPowerList(List<ModuleVo> powerList) {
		if (!com.blueocean_health.care.management.common.base.string.StringUtils.isEmpty(powerList)
				&& powerList.size() > 0) {
			List<ModuleVo> newModuleList = new ArrayList<>();
			ModuleVo appModule = new ModuleVo();
			appModule.setName(ProjectTypeEnum._1.getVal());
			appModule.setValue(ProjectTypeEnum._1.getKey());
			ModuleVo projectModule = new ModuleVo();
			projectModule.setName(ProjectTypeEnum._2.getVal());
			projectModule.setValue(ProjectTypeEnum._2.getKey());

			List<ModuleVo> appList = new ArrayList<>();
			List<ModuleVo> projectList = new ArrayList<>();

			for (ModuleVo moduleVo : powerList) {
				if (Integer.parseInt(moduleVo.getValue()) < 200) {
					// 项目端
					projectList.add(moduleVo);
				} else {
					// app端
					appList.add(moduleVo);
				}
				System.out.println(moduleVo);
			}
			if (!appList.isEmpty()) {
				appModule.setItems(appList);
				newModuleList.add(appModule);
			}
			if (!projectList.isEmpty()) {
				projectModule.setItems(projectList);
				newModuleList.add(projectModule);
			}

			powerList = newModuleList;
		}
		return powerList;
	}

	/**
	 * 获得在某组织/项目下用户的权限
	 * 
	 * @param userId
	 *            用户ID
	 * @param teamId
	 *            组织ID
	 */
	@Override
	public List<ModuleVo> getUserPermissions(String userId, String teamId) {
		// 1、查询组织/项目的可用模块
		// 2、查询用户在某组织中的所有角色(user_team_v)
		// 2.1 查询出的角色的权限列表取并集
		// 3、组织可用模块和权限列表取交集
		Map<String, String> paramsMap = new HashMap<>();
		paramsMap.put("userId", userId);
		paramsMap.put("teamId", teamId);
		if (StringUtils.isEmpty(teamId)) {
			logger.info("userId" + userId + "teamId:" + teamId + "用户没有对应组织-没有任何操作权限！！！" + TimeUtils.getTimesTamp());
			return new ArrayList<>();
		}
		// 用户拥有的权限列表
		List<Map<String, String>> powerList = roleMapper.findRolePowerByUserIdAndTeamId(paramsMap);
		if (powerList.isEmpty()) {
			logger.info("userId" + userId + "teamId:" + teamId + "用户拥有的权限列表为空-没有任何操作权限！！！" + TimeUtils.getTimesTamp());
			return new ArrayList<>();
		}
		// 通过权限列表反推出可用模块
		Set<String> moduleSet = new HashSet<>();
		powerList.forEach(moduleMap -> {
			String powerCode = moduleMap.get("value");
			List<String> asList = Arrays.asList(powerCode.split("-"));
			for (int i = 0; i < asList.size() - 1; i++) {
				StringBuffer sb = new StringBuffer();
				for (int j = 0; j <= i; j++) {
					sb.append(asList.get(j) + "-");
				}
				moduleSet.add(sb.substring(0, sb.length() - 1));
			}
		});
		String moduleStr = StringUtils.join(moduleSet.toArray(), ",");
		if (StringUtils.isEmpty(moduleStr)) {
			logger.info("userId" + userId + "teamId:" + teamId + "没有任何模块权限！！！" + TimeUtils.getTimesTamp());
			return new ArrayList<>();
		}
		paramsMap.put("moduleStr", moduleStr);
		// 组织可用模块和权限集合取交集
		List<ModuleVo> permissionList = roleMapper.findUserPermissionsByUserIdAndTeamId(paramsMap);
		return permissionList;
	}

	/**
	 * 获得在某组织/项目下用户的权限，包含  module_code, power_code
	 * 
	 * @param userId 
	 *            用户ID
	 * @param teamId
	 *            组织ID
	 */
	@Override
	public List<String> getUserPermissionsNew(String userId, String teamId) {
		return RoleServiceImpl.getNewPermissions(getPermissionsNew(userId, teamId));
	}
	
	/**
	 * 获得在某组织/项目下用户的权限，只包含power_code
	 * 
	 * @param userId 
	 *            用户ID
	 * @param teamId
	 *            组织ID
	 */
	@Override
	public List<String> getPermissionsNew(String userId, String teamId) {
		Map<String, String> paramsMap = new HashMap<>();
		paramsMap.put("userId", userId);
		paramsMap.put("teamId", teamId);
		if (StringUtils.isEmpty(teamId)) {
			logger.info("userId" + userId + "teamId:" + teamId + "用户没有对应组织-没有任何操作权限！！！" + TimeUtils.getTimesTamp());
			return new ArrayList<>();
		}
		//1.权限列表取并集
		List<String> permissionList = roleMapper.findAllUserPermissionByUserIdAndTeamId(paramsMap);
		if (null != permissionList && permissionList.size() > 0) {
			permissionList = permissionList.stream().filter(p -> !StringUtils.isEmpty(p)).collect(Collectors.toList());
		}
		if (null == permissionList || permissionList.size() <= 0) {
			return null;
		}
		//2.模块的所属权限
		List<String> teamPowerList = roleMapper.findTeamPowersByTeamId(paramsMap);
		if (null != teamPowerList && teamPowerList.size() > 0) {
			teamPowerList = teamPowerList.stream().filter(t -> !StringUtils.isEmpty(t)).collect(Collectors.toList());
		}
		if (null == teamPowerList || teamPowerList.size() <= 0) {
			return null;
		}
		
		// 3.组织可用模块和权限列表取交集
		List<String> results = new ArrayList<>();
		for (String t : teamPowerList) {
			if (!StringUtils.isEmpty(t) && permissionList.contains(t)) {
				results.add(t);
			}
		}
		return results;
	}

	/**
	 * 获得组织对应模块的所有权限清单
	 */
	@Override
	public List<ModuleVo> getPowerByOrg(String orgId) {
		// 获取组织对应的可用模块
		String modules = moduleMapper.findByTeamId(orgId);
		Map<String, String> paramsMap = new HashMap<>();
		paramsMap.put("modules", modules);
		paramsMap.put("orgId", orgId);
		List<ModuleVo> permissionList = powerMapper.findPowerByOrg(paramsMap);
		return permissionList;
	}

}
